const fs = require("fs");
const path = require("path");
// 导入执行js的模块
const { execSync } = require("child_process");

const sourceDir = "C:\\Program Files (x86)\\英语口语学习王";
const sourceBookDir = path.join(sourceDir, "Book");
const sourceBookSounce = path.join(sourceDir, "Sound");

const targetDir = path.join(__dirname, "../resources/courses");

// 从sourceBookDir下获取全部目录作为课程
const allBooks = fs.readdirSync(sourceBookDir);
// 遍历课程并获取文件夹下的文件个数
allBooks.forEach((bookName) => {
  console.log(`==========================>`);
  console.log(`正在处理课程${bookName}`);
  console.log(`==========================>`);
  const bookPath = path.join(sourceBookDir, bookName);
  const bookFiles = fs.readdirSync(bookPath);
  console.log(`课程${bookName}包含${bookFiles.length}个文件`);
  const bookFilesCount = bookFiles.length;
  const bookSounceDir = path.join(sourceBookSounce, bookName);
  if (!fs.existsSync(bookSounceDir)) {
    console.log(`课程${bookName}的音频文件目录不存在`);
    return;
  }
  // 获取课程的音频文件个数
  const bookSounceFiles = fs.readdirSync(bookSounceDir);
  console.log(`课程${bookName}的音频文件个数是${bookSounceFiles.length}`);
  const bookSounceFilesCount = bookSounceFiles.length;
  if (bookSounceFilesCount < 2) {
    return;
  }
  // 在targetDir下创建bookName的文件夹
  const targetBookDir = path.join(targetDir, bookName);
  if (!fs.existsSync(targetBookDir)) {
    fs.mkdirSync(targetBookDir);
  } else {
    console.log(`课程${bookName}已存在`);
    // 执行node convertDatToJson.js
    execSync(`node ./tools/convertDatToJson.js "${targetDir}/${bookName}"`);    
    return;
  }
  // 将bookFiles拷贝到targetBookDir下
  bookFiles.forEach((fileName) => {
    const sourceFilePath = path.join(bookPath, fileName);
    const targetFilePath = path.join(targetBookDir, fileName);
    fs.copyFileSync(sourceFilePath, targetFilePath);
  });
  // 将bookSounceFiles拷贝到targetBookDir下
  bookSounceFiles.forEach((fileName) => {
    const sourceFilePath = path.join(bookSounceDir, fileName);
    const targetFilePath = path.join(targetBookDir, fileName);
    fs.copyFileSync(sourceFilePath, targetFilePath);
  });
  // 获取targetDir下index.json文件内容
  const indexFilePath = path.join(targetDir, "index.json");
  let indexFileContent = fs.readFileSync(indexFilePath, "utf-8");
  indexFileContent = JSON.parse(indexFileContent);
  let bookIdx = indexFileContent.length;
  indexFileContent.push({
    id: bookIdx + 1,
    title: bookName,
    description: `${bookName}, 共${bookSounceFilesCount}课`,
    level: "intermediate",
    category: "default",
    isActive: true,
    path: bookName
  });
  fs.writeFileSync(indexFilePath, JSON.stringify(indexFileContent, null, 2));
});
